<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Group extends Controller_Admin {

    public function before() {
        parent::before();
        $this->setActive_menu_left('group');
    }

    public function action_list() {
        $this->setActive_menu_left('grouplist');
        $a_js = array('include/group/list', 'include/group/group_objects', 'knockout', 'ace-elements.min', 'ace.min');
        $this->add_js($a_js);
        $a_css = array('select2');
        $this->add_css($a_css);
        $breadcrumbs = array(
            "Group" => array('onclick' => '', 'href' => 'javascript:;'),
            "List Group" => "",
        );
        $a_pagination = Kohana::$config->load("pagination");
        $page = Arr::get($_GET, 'page') == "" ? 1 : Arr::get($_GET, 'page');
        $items_per_page = Arr::get($_GET, 'size') != "" ? Arr::get($_GET, 'size') : Arr::path($a_pagination, 'admin.items_per_page');
        $to = $page * $items_per_page;
        $offset = $to - $items_per_page;
        $a_pagination->admin["items_per_page"] = $items_per_page;
        $s_group = new Model_Service_Group;

        $n_type = Arr::get($_GET, 'type');
        $fillter = null;
        if (!empty($n_type)) {
            $fillter = array('type' => $n_type);
        }
        $fillter = $this->get_filter($fillter, array('name' => 'like', 'id' => '=', 'description' => 'like'));
        $en_group = $s_group->load_all(
                false, $offset, $items_per_page, $fillter, $this->get_sort(null, 'name')
        );
        $n_count_all = $s_group->load_all(true, null, null, $fillter);
        Arr::set_path($a_pagination, 'admin.total_items', $n_count_all);
        $pagination = new Pagination(Arr::get($a_pagination, 'admin'));

        $a_user = $this->_user;


        $this->template->content = $this->template->content = View::factory("admin/group/list")
                ->set('en_group', $en_group)
                ->set('size', $items_per_page)
                ->set('pagination', $pagination)
                ->set('a_user', $a_user)
                ->set('breadcrumbs', $breadcrumbs);
    }

    public function action_get_data() {
        header('Content-type: application/json');
        $search = Arr::get($_REQUEST, "textsearch");
        $string = urldecode($search);
        $filter = array();
        if (!empty($_REQUEST['textsearch'])) {
            $textsearch = trim($_REQUEST['textsearch']);
            $filter['where open'] = null;
            $filter['name'] = array('or like' => $textsearch);
            $filter['where close'] = null;
        }

        $a_pagination = Kohana::$config->load("pagination");
        $page = Arr::get($_GET, 'page') == "" ? 1 : Arr::get($_GET, 'page');
        $items_per_page = Arr::get($_GET, 'size') != "" ? Arr::get($_GET, 'size') : Arr::path($a_pagination, 'admin.items_per_page');
        $to = $page * $items_per_page;
        $offset = $to - $items_per_page;
        $a_pagination->admin["items_per_page"] = $items_per_page;

        $s_group = new Model_Service_Group();


        $en_group = $s_group->load_all(false, $offset, $items_per_page, $filter);
        $count = $s_group->load_all(true, null, null, $filter);

        Arr::set_path($a_pagination, 'admin.total_items', $count);

        $pagination = new Pagination(Arr::get($a_pagination, 'admin'));
        $a_data = array();
        $result["error"] = 0;
        if (!empty($en_group)) {
            $result = array();
            foreach ($en_group as $item) {
                $a_group = $item->get_data();
                $result["id"] = $a_group->getId();
                $result["name"] = $a_group->getName();
               
                $result["description"] = $a_group->getPage();
                $a_data["data"][] = $result;
            }
        } else {
            $result["error"] = 1;
            $result["msg"] = "This doesn't have any group permission";
            $a_data["data"][] = $result;
            echo json_encode($a_data);
            die;
        }
        $a_data['pagination'] = $pagination->render();
        echo json_encode($a_data);
        die;
    }

    public function action_add() {
        $this->setActive_menu_left('groupadd');
        $this->add_js(array('include/group/group_add', 'jquery.multi-select', 'jquery.validate.min', 'ace-elements.min', 'ace.min'));
        $this->add_css(array('multi-select', 'group'));
        $breadcrumbs = array(
            "Group" => "",
            "List" => array('onclick' => '', 'href' => 'javascript:;'),
            "Add Group" => ""
        );
        $a_user = $this->_user;
       
        //get permission controller
        $s_p_controller = new Model_Service_Permission_Controller;
        $a_p_controller = $s_p_controller->load_all();
        $this->template->content = View::factory("admin/group/add")
                ->set('breadcrumbs', $breadcrumbs)
                ->set('a_user', $a_user)
                
                ->set('a_p_controller', $a_p_controller)
        ;
    }

    public function action_savegroup() {
        header('Content-type: application/json');
        $namegroup = Arr::get($_REQUEST, "namegroup");
        $description = Arr::get($_REQUEST, "description");
       
        $permission = Arr::get($_REQUEST, "permission_id");
        $result = array();
        //add group 
        $s_group = new Model_Service_Group();
        // check group
        $count = $s_group->get_group_by_name($namegroup, true);
        if ($count > 0) {
            $result["error"] = 1;
            $result["msg"] = "Group is existing";
            echo json_encode($result);
            die;
        } else {
            $entity_group = new Domain_Entities_Group();
            $entity_group->setName(trim($namegroup));
            $entity_group->setDescription($description);
           
            $result_add_group = $s_group->insert($entity_group);
            // add permission
            if (!empty($result_add_group)) {
                $o_group = $result_add_group->get_data();
                $group_id = $o_group->getId();

                if (empty($permission) && is_array($permission)) {
                    // do nothing
                    die;
                } else {

                    $s_group_permission = new Model_Service_Group_Permission();
                    $entity_group_permission = new Domain_Entities_Group_Permission();
                    foreach ($permission as $permission_id) {

                        $entity_group_permission->setGroup_Id($group_id);
                        $entity_group_permission->setPermission_Id($permission_id);
                        $s_group_permission->insert($entity_group_permission);
                    }
                }
            }
        }
        $result["error"] = 0;
        $result["msg"] = "Add Group Success";
        echo json_encode($result);
        die;
    }

    public function action_edit() {
        $this->setActive_menu_left('groupedit');
        $this->add_js(array('include/group/group_edit', 'jquery.multi-select', 'jquery.validate.min', 'ace-elements.min', 'ace.min'));
        $this->add_css(array('multi-select', 'group'));
        $o_message = Controller_Helper_Message::get_instance();
        $s_group = new Model_Service_Group;
        $group_id = Arr::get($_REQUEST, 'id');
        $a_group = $s_group->load($group_id);
        if (empty($a_group)) {
            if (!empty($this->_redirect)) {
                $this->redirect($this->_redirect);
            } else {
                $this->redirect(URL::base() . 'admin/group/list');
            }
        }
        $o_group = $a_group->get_data();
        $a_group_id = $o_group->getId();
        if (empty($a_group_id)) {
            if (!empty($this->_redirect)) {
                $this->redirect($this->_redirect);
            } else {
                $this->redirect(URL::base() . 'admin/group/list');
            }
        }
        // get group permission
        $s_gp = new Model_Service_Group_Permission();
        $a_gp = $s_gp->load_all(
                false, null, null, array('group_id' => $group_id)
        );
        $a_permission_id = array();
        if ($a_gp != null && !empty($a_gp[0])) {
            foreach ($a_gp as $o_gp) {
                $o_enity_gp = $o_gp->get_data();
                $a_permission_id[] = $o_enity_gp->getPermission_Id();
            }
        }
        $breadcrumbs = array(
            "Group" => "",
            "List" => array('onclick' => '', 'href' => 'javascript:;'),
            "Edit Group" => ""
        );
        //get permission controller
        $s_p_controller = new Model_Service_Permission_Controller;
        $a_p_controller = $s_p_controller->load_all();
      

        $this->template->content = View::factory("admin/group/edit")
                ->set('breadcrumbs', $breadcrumbs)
                ->set('a_group', $a_group)
                
                ->set('a_permission_id', $a_permission_id)
                ->set('a_p_controller', $a_p_controller);
    }

    public function action_save_edit_group() {
        header('Content-type: application/json');
        $group_id = Arr::get($_GET, 'id');
        $namegroup = Arr::get($_REQUEST, "namegroup");
        $description = Arr::get($_REQUEST, "description");
       
        $permission = Arr::get($_REQUEST, "permission_id");
        $result = array();
        $s_group = new Model_Service_Group();
        $a_group = $s_group->load($group_id)->get_data();
        $count_group = $s_group->get_group_by_name($namegroup, true);
        if ($count_group > 0) {
            $result["error"] = 1;
            $result["msg"] = "Group is existing";
            echo json_encode($result);
            die;
        }
        if ($a_group->getId() < 0) {
            $result["error"] = 1;
            $result["msg"] = "Group isn't existing";
            echo json_encode($result);
            die;
        } else {
            //update group
            $a_group->setName($namegroup);
            $a_group->setDescription($description);
            
            $o_result = $s_group->update($a_group);
            if (!empty($o_result)) {
                $n_id_group = $group_id;
                $s_group_permission = new Model_Service_Group_Permission();
                //delete all by groupid
                $s_group_permission->delete_by_groupids($n_id_group);
                if (empty($permission) || !is_array($permission)) {
                    // notthing
                } else {

                    // update group_permission
                    foreach ($permission as $n_permission_id) {
                        $o_entity_group_permission = new Domain_Entities_Group_Permission();
                        $o_entity_group_permission->setPermission_Id($n_permission_id);
                        $o_entity_group_permission->setGroup_Id($n_id_group);
                        $s_group_permission->insert($o_entity_group_permission);
                    }
                }
            }
        }
        $result["error"] = 0;
        $result["msg"] = "Update Group success";
        echo json_encode($result);
        die;
    }

    public function action_deleted() {
        header('Content-type: application/json');
        $id = Arr::get($_REQUEST, 'id');
        $s_group = new Model_Service_Group();
        $a_group = $s_group->load($id)->get_data();
        $s_group_permission = new Model_Service_Group_Permission();
        $a_data = array();
        $a_data['error'] = 0;
        if ((int) $a_group->getId() <= 0) {
            $a_data['error'] = 1;
            $a_data['msg'] = "Group is not exsting.";
            echo json_encode($a_data);
            die;
        }
        $s_group->delete($id);
        $s_group_permission->delete_by_groupids($id);

        $a_data['msg'] = Kohana::message('en/admin/department/success', 'delete');
        $a_data['error'] = 0;
        echo json_encode($a_data);
        die;
    }

}

?>
